package org.grayrabbit.cms.util;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Scanner;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author 蔡万东
 * 
 */
public class AESEncipher {

	private static AESEncipher aes = null;

	// 灰兔子的密钥，可更改，只能为英文、数字、一般的常用字符（特殊字符最好不要用），全角字符不可用
	private final static String key = "grayrabbit";

	public static synchronized AESEncipher getInstance() {
		if (aes == null) {
			aes = new AESEncipher();
		}
		return aes;
	}

	/**
	 * AES加密算法
	 */
	public AESEncipher() {
	}

	/**
	 * 加密
	 * 
	 * @param content
	 *            需要加密的内容
	 * @param keyWord
	 *            加密密钥
	 * @return byte[] 加密后的字节数组
	 */
	public byte[] encrypt(String content, String keyWord) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
			secureRandom.setSeed(keyWord.getBytes());
			kgen.init(128, secureRandom);
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");// 创建密码器
			byte[] byteContent = content.getBytes("utf-8");
			cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
			byte[] result = cipher.doFinal(byteContent);
			return result; // 加密
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * @param content
	 *            需要加密的内容
	 * @param password
	 *            加密密钥
	 * @return String 加密后的字符串
	 */
	public String encrypttoStr(String content, String password) {
		return parseByte2HexStr(encrypt(content, password));
	}

	/**
	 * 解密
	 * 
	 * @param content
	 *            待解密内容
	 * @param keyWord
	 *            解密密钥
	 * @return byte[]
	 */
	public byte[] decrypt(byte[] content, String keyWord) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
			secureRandom.setSeed(keyWord.getBytes());
			kgen.init(128, secureRandom);
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");// 创建密码器
			cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
			byte[] result = cipher.doFinal(content);
			return result; // 加密
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * @param content
	 *            待解密内容(字符串)
	 * @param keyWord
	 *            解密密钥
	 * @return byte[]
	 */
	public byte[] decrypt(String content, String keyWord) {
		return decrypt(parseHexStr2Byte(content), keyWord);
	}

	/**
	 * 将二进制转换成16进制
	 * 
	 * @param buf
	 * @return String
	 */
	public String parseByte2HexStr(byte buf[]) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < buf.length; i++) {
			String hex = Integer.toHexString(buf[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}

	/**
	 * 将16进制转换为二进制
	 * 
	 * @param hexStr
	 * @return byte[]
	 */
	public byte[] parseHexStr2Byte(String hexStr) {
		if (hexStr.length() < 1)
			return null;
		byte[] result = new byte[hexStr.length() / 2];
		for (int i = 0; i < hexStr.length() / 2; i++) {
			int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
			int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
					16);
			result[i] = (byte) (high * 16 + low);
		}
		return result;
	}

	/**
	 * 使用方法：AESEncipher.getInstance().arEncrypt(str)；
	 * 灰兔子加密方法，传入需要加密的字符串，返回加密后的密文，已加密的不再加密
	 * 
	 * @param msg
	 * @return
	 */
	public String arEncrypt(String msg) {
		if (msg == null) {
			return null;
		}
		if ("".equals(msg) || msg.startsWith("%@%")) {
			return msg;
		} else {
			return "%@%" + encrypttoStr(msg, key);
		}
	}

	/**
	 * 使用方法： AESEncipher.getInstance().arDecrypt(str);
	 * 灰兔子解密方法，传入需要解密的字符串，返回解密的结果，不是通过上述加密方法加密的返回原值
	 * 
	 * @param msg
	 * @return
	 */
	public String arDecrypt(String msg) {
		if (msg == null) {
			return null;
		} else {
			if (msg.length() > 3 && msg.startsWith("%@%")) {
				return new String(decrypt(msg.substring(3), key));
			} else {
				return msg;
			}
		}

	}

	public static void main(String[] args) {
		System.out.println("请输入明文：");
		Scanner scanner = new Scanner(System.in);
		String str1 = scanner.next();
		String str = AESEncipher.getInstance().arEncrypt(str1);
		System.out.println("加密后的值为：");
		System.out.println(str);
		System.out.println("解密后的值为：");
		System.out.println(AESEncipher.getInstance().arDecrypt(str));
	}
}